<template>
  <div class="profile-container">
    <!-- 头像和用户名区域 -->
    <div class="profile-header">
      <div class="avatar-container">
        <el-upload
          class="avatar-uploader"
          :http-request="customUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <el-avatar
            :size="64"
            class="avatar"
            :src="userInfo.avatar"
          >
            <el-icon><User /></el-icon>
          </el-avatar>
          <div class="avatar-hover-mask">
            <el-icon><Upload /></el-icon>
          </div>
        </el-upload>
      </div>
    </div>

    <!-- 表单区域 -->
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="70px"
      class="profile-form"
    >
      <el-form-item label="用户名" prop="username" required>
        <el-input 
          v-model="form.username" :disabled="true"
          :input-style="{ height: '40px' }"
        />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input 
          v-model="form.email"
          placeholder="请输入邮箱"
          :input-style="{ height: '40px' }"
        />
      </el-form-item>

      <el-form-item label="昵称" prop="nickname">
        <el-input 
          v-model="form.nickname"
          placeholder="请输入昵称"
          :input-style="{ height: '40px' }"
        />
      </el-form-item>

      <el-form-item label="角色" prop="role">
        <el-input 
          v-model="form.role" :disabled="true"
          :input-style="{ height: '40px' }"
        />
      </el-form-item>

      <el-form-item label="密码" class="password-item">
        <el-button 
          type="primary" 
          @click="showResetPassword"
          class="reset-btn"
        >
          重置密码
        </el-button>
      </el-form-item>

      <!-- Add buttons container -->
      <el-form-item>
        <div class="button-container">
          <el-button type="primary" @click="handleUpdate">更新</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '@/store/user'
import { ElMessage } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import defaultAvatar from '@/assets/icon/default-avatar.png'
import {CreateResource} from '@/api/resource'
import { CreateResourceRequest, Resource} from "@/types/proto/api/v1/resource_service";
import { UpdateUser } from '@/api/user'
import { useRouter } from 'vue-router'
import type { UpdateUserRequest, User } from '@/types/proto/api/v1/user_service'

const userStore = useUserStore()
const formRef = ref<FormInstance>()
const userInfo = reactive({
  nickname: userStore.userInfo?.nickname || '',
  email: userStore.userInfo?.email || '',
  avatar: userStore.userInfo?.avatarUrl || defaultAvatar,
  avatarUrl:  ''
})

// Add onMounted hook
onMounted(() => {
  if (userStore.userInfo?.avatarUrl) {
    const avatarUrl = userStore.userInfo.avatarUrl;
    if (avatarUrl.startsWith('data:image')) {
      // Convert base64 to Blob
      const parts = avatarUrl.split(';base64,');
      const contentType = parts[0].split(':')[1];
      const raw = window.atob(parts[1]);
      const rawLength = raw.length;
      const uInt8Array = new Uint8Array(rawLength);
      
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      
      const blob = new Blob([uInt8Array], { type: contentType });
      userInfo.avatar = URL.createObjectURL(blob);
    } else {
      userInfo.avatar = avatarUrl;
    }
  }
})

const form = reactive({
  username: userStore.userInfo?.nickname || '',
  email: userStore.userInfo?.email || '',
  nickname: userStore.userInfo?.nickname||'',
  role: userStore.userInfo?.role||''
})

const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
})

const router = useRouter()

const showResetPassword = () => {
  // TODO: 实现重置密码功能
  ElMessage.info('重置密码功能待实现')
}

const customUpload = async (options: any) => {
  try {
    const file = options.file
    // 先创建本地预览
    const localUrl = URL.createObjectURL(file)
    userInfo.avatar = localUrl // 立即更新预览
    const avatarUrl = await new Promise<string>((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = reject;
      reader.readAsDataURL(file);
    });
    userInfo.avatarUrl = avatarUrl
  
  } catch (error) {
    console.error("custom upload error:", error)
    ElMessage.error('上传失败')
    options.onError(error)
  }
}

const handleAvatarSuccess = (res: Resource) => {
  ElMessage.success('头像已准备好，请点击更新按钮保存修改')
}

const beforeAvatarUpload = (file: File) => {
  const isValidFormat = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isValidFormat) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
  }
  return isValidFormat && isLt2M
}

const handleUpdate = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let u = { ...userStore.userInfo } // Create a shallow copy
        const updateMask = [];
        if (!u) {
          return
        }

        // Remove timestamp fields to avoid conversion issues
        delete u.createTime
        delete u.updateTime

        if (form.username !== u.username) {
          updateMask.push("username")
          u.username = form.username
        }

        if (form.nickname !== u.nickname) {
          updateMask.push("nickname")
          u.nickname = form.nickname
        }

        if (form.email !== u.email) {
          updateMask.push("email")
          u.email = form.email
        }

        if (userInfo.avatarUrl !== u.avatarUrl) {
          updateMask.push("avatar")
          u.avatarUrl = userInfo.avatarUrl
        }
        const updateRequest: UpdateUserRequest = {
          user: u as User,
          updateMask: updateMask,
        }
        
        UpdateUser(updateRequest).then((res: User) => {
          userStore.userInfo = res
          ElMessage.success('更新成功')
          router.back() 
        })
      } catch (error) {
        console.error('Update failed:', error)
        ElMessage.error('更新失败')
      }
    }
  })
}

const handleCancel = () => {
  router.back()
}

</script>

<style scoped>
.profile-container {
  padding: 20px 30px;
  background-color: #fff;
  border-radius: 8px;
}

.profile-header {
  display: flex;
  align-items: center;
  margin-bottom: 40px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.avatar-container {
  margin-right: 16px;
}

.avatar {
  background-color: hsl(210, 25%, 95%);
  font-size: 24px;
}

.profile-form {
  max-width: 400px;
}

.profile-form :deep(.el-form-item) {
  margin-bottom: 24px;
}

.profile-form :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.profile-form :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #409EFF inset;
}

.profile-form :deep(.el-input.is-disabled .el-input__wrapper) {
  box-shadow: 0 0 0 1px #e4e7ed inset;
  background-color: #f5f7fa;
}

.reset-btn {
  width: 100%;
  height: 40px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__wrapper) {
  padding: 0 12px;
}

:deep(.el-input__inner) {
  font-size: 14px;
}

.avatar-uploader {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

.avatar-hover-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-uploader:hover .avatar-hover-mask {
  opacity: 1;
}

.button-container {
  display: flex;
  gap: 12px;
  justify-content: flex-start;
}
</style>
